
import os
import tkinter as tk
from tkinter import filedialog, messagebox
import xml.etree.ElementTree as ET
import pandas as pd

class XmlToCsvConverter:
    def __init__(self):
        self.root = tk.Tk()
        self.root.title("XML转CSV转换器")
        self.root.geometry("600x220")
        
        self.setup_ui()
        
    def setup_ui(self):
        # 主容器
        main_frame = tk.Frame(self.root, padx=20)
        main_frame.pack(fill=tk.BOTH, expand=True, pady=10)
        
        # 输入路径部分
        input_frame = tk.Frame(main_frame)
        input_frame.pack(fill=tk.X, pady=(10,0))
        
        # 红色提示文本（上方）
        hint_frame = tk.Frame(input_frame)
        hint_frame.pack(fill=tk.X)
        tk.Label(hint_frame, width=len("输入路径:")).pack(side=tk.LEFT)
        tk.Label(hint_frame, text="输入XML文件的根目录", 
                fg="red", font=("Arial", 9), anchor="w").pack(side=tk.LEFT)
        
        # 输入路径标签和浏览按钮
        input_subframe = tk.Frame(input_frame)
        input_subframe.pack(fill=tk.X, pady=5)
        tk.Label(input_subframe, text="输入路径:").pack(side=tk.LEFT)
        self.input_entry = tk.Entry(input_subframe, width=40)
        self.input_entry.pack(side=tk.LEFT, padx=5, expand=True, fill=tk.X)
        tk.Button(input_subframe, text="浏览...", command=self.select_input).pack(side=tk.LEFT)
        
        # 输出路径部分
        output_frame = tk.Frame(main_frame)
        output_frame.pack(fill=tk.X, pady=(15,0))
        
        # 红色提示文本（上方）
        hint_frame_out = tk.Frame(output_frame)
        hint_frame_out.pack(fill=tk.X)
        tk.Label(hint_frame_out, width=len("输出路径:")).pack(side=tk.LEFT)
        tk.Label(hint_frame_out, text="输入CSV的输出目录", 
                fg="red", font=("Arial", 9), anchor="w").pack(side=tk.LEFT)
        
        # 输出路径标签和浏览按钮
        output_subframe = tk.Frame(output_frame)
        output_subframe.pack(fill=tk.X, pady=5)
        tk.Label(output_subframe, text="输出路径:").pack(side=tk.LEFT)
        self.output_entry = tk.Entry(output_subframe, width=40)
        self.output_entry.pack(side=tk.LEFT, padx=5, expand=True, fill=tk.X)
        tk.Button(output_subframe, text="浏览...", command=self.select_output).pack(side=tk.LEFT)
        
        # 确定按钮
        confirm_frame = tk.Frame(main_frame)
        confirm_frame.pack(side=tk.BOTTOM, pady=15, fill=tk.X)
        tk.Button(confirm_frame, text="确定", width=15, command=self.convert_xml_to_csv).pack()
    
    def select_input(self):
        path = filedialog.askdirectory(title="选择输入文件夹")
        if path: 
            self.input_entry.delete(0, tk.END)
            self.input_entry.insert(0, path)
    
    def select_output(self):
        path = filedialog.askdirectory(title="选择输出文件夹")
        if path: 
            self.output_entry.delete(0, tk.END)
            self.output_entry.insert(0, path)
    
    def convert_xml_to_csv(self):
        input_path = self.input_entry.get()
        output_path = self.output_entry.get()
        
        if not input_path or not output_path:
            messagebox.showerror("错误", "请选择输入和输出路径")
            return
        
        try:
            xml_files = [f for f in os.listdir(input_path) if f.endswith('.xml')]
            if not xml_files:
                messagebox.showwarning("警告", "输入路径中没有找到XML文件")
                return
            
            for xml_file in xml_files:
                xml_path = os.path.join(input_path, xml_file)
                tree = ET.parse(xml_path)
                root = tree.getroot()
                
                data = []
                for elem in root:
                    row = {}
                    for subelem in elem:
                        row[subelem.tag] = subelem.text
                    data.append(row)
                
                csv_file = os.path.splitext(xml_file)[0] + '.csv'
                csv_path = os.path.join(output_path, csv_file)
                pd.DataFrame(data).to_csv(csv_path, index=False)
            
            messagebox.showinfo("完成", f"成功转换 {len(xml_files)} 个XML文件")
            self.root.destroy()
            
        except Exception as e:
            messagebox.showerror("错误", f"转换过程中发生错误: {str(e)}")

if __name__ == "__main__":
    app = XmlToCsvConverter()
    app.root.mainloop()
